<?php
namespace QuestionPlus\Service\Export\QuestionExport;

class DocMaker
{
    var $headers = array();
    var $headers_exists = array();
    var $files = array();
    var $boundary;

    private function SetHeader($header)
    {
        $this->headers[] = $header;
        $key = strtolower(substr($header, 0, strpos($header, ':')));
        $this->headers_exists[$key] = TRUE;
    }

    private function SetDate()
    {
        $date = time();
        $date = date('D, d M Y H:i:s O', $date);
        $this->SetHeader("Date: $date");
    }

    private function SetBoundary()
    {
        $this->boundary = '--' . strtoupper(md5(mt_rand())) . '_MULTIPART_MIXED';
    }

    public function AddContents($filepath, $mimetype, $filecont)
    {

        $filecont = chunk_split(base64_encode($filecont), 76);
        $encoding = 'base64';

        $this->files[] = array(
            'filepath' => $filepath,
            'mimetype' => $mimetype,
            'filecont' => $filecont,
            'encoding' => $encoding
        );
    }

    public function GetFile()
    {
        $this->SetDate(NULL, TRUE);
        $this->SetBoundary();

        $contents = implode("\r\n", $this->headers);
        $contents .= "\r\n";
        $contents .= "MIME-Version: 1.0\r\n";
        $contents .= "Content-Type: multipart/related;\r\n";
        $contents .= "\tboundary=\"{$this->boundary}\";\r\n";
        $contents .= "\ttype=\"" . $this->files[0]['mimetype'] . "\"\r\n";
        $contents .= "X-MimeOLE: \r\n";
        $contents .= "\r\n";
        foreach ($this->files as $file) {
            $contents .= "--{$this->boundary}\r\n";
            $contents .= "Content-Type: $file[mimetype]\r\n";
            $contents .= "Content-Transfer-Encoding: $file[encoding]\r\n";
            $contents .= "Content-Location: $file[filepath]\r\n";
            $contents .= "\r\n";
            $contents .= $file['filecont'];
            $contents .= "\r\n";
        }
        $contents .= "--{$this->boundary}--\r\n";
        return $contents;
    }

    public function GetMimeType($filename)
    {
        $pathinfo = pathinfo($filename);
        switch ($pathinfo['extension']) {
            case 'html': $mimetype = 'text/html'; break;
            case 'css': $mimetype = 'text/css'; break;
            case 'jpg': $mimetype = 'image/jpeg'; break;
            case 'jpeg': $mimetype = 'image/jpeg'; break;
            case 'jpe': $mimetype = 'image/jpeg'; break;
            case 'gif': $mimetype = 'image/gif'; break;
            case 'png': $mimetype = 'image/png'; break;
            default: $mimetype = 'application/octet-stream'; break;
        }
        return $mimetype;
    }
}